<template>
    <div>
        <div v-show="activeStatu">
            <el-card class="box">
                <div class="card-padding">
                    <!-- 搜索筛选名称或标题 -->
                    <div class="flex">
                        <div class="category-title">分类标题</div>
                        <div class="time_top">创建时间</div>
                    </div>
                    <div class="flexBox">
                        <div> 
                            <el-input v-model.trim="inputed" @input="filters" placeholder="输入内容" class="search-input">
                                <template #prefix>
                                    <el-icon class="el-input__icon">
                                        <search />
                                    </el-icon>
                                </template>
                            </el-input>
                        </div>
                        <div class="date-picker-container">
                            <el-date-picker class="date-picker" @change="data_filters" v-model="time" type="daterange"
                                range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" />
                        </div>
                    </div>
                    <div class="button-group">
                        <div><el-button type="primary" @click="add" class="add_class">
                                新增</el-button>
                        </div>
                        <el-button type="danger" class="delelist" @click="deleList">批量删除</el-button>
                    </div>
                    <!-- table表格数据展示 -->
                    <div> 
                        <el-table :data="activeList.slice((currentPage - 1) * pageSize, currentPage * pageSize)"
                                class="data-table" :cell-style="{ 'text-align': 'center' }" lazy="true"
                                height="auto" v-el-table-infinite-scroll="handleTableScroll"
                                :header-cell-style="{ 'text-align': 'center' }" @selection-change="handleSelectionChange">
                            <el-table-column type="selection" fixed="left" />
                            <el-table-column prop="id" label="序号" fixed="left" />
                            <el-table-column prop="title" label="分类名称" show-overflow-tooltip />
                            <el-table-column prop="createtime" label="创建时间" />
                            <el-table-column label="操作" width="250" fixed="right">
                                <template #default="scope">
                                    <div class="handle">
                                        <div @click="edit(scope.row)" class="edit-btn">编辑</div>
                                        <div class="button-spacing"></div>
                                        <div @click="deletes(scope.row)" class="delete-btn">删除</div>
                                    </div>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                    <div class="paging">
                        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                            :page-sizes="[5, 10, 20, 50]" :small="small" :disabled="disabled" background
                            layout="total, sizes, prev, pager, next, jumper" :total="activeList.length" />
                    </div>
                    <!-- 删除弹窗 -->
                    <el-dialog title="删除" v-model="centerDialogVisible" width="30%" center>
                        <div class="dialog-message">确认删除该娱乐吗?</div>
                        <div class="dialog-buttons">
                            <el-button @click="centerDialogVisible = false">取 消</el-button>
                            <el-button type="primary" @click="deleteid">确 定</el-button>
                        </div>
                    </el-dialog>
                </div>
                <el-dialog v-model="shows" title="是否要删除" center width="20vw">
                    <el-button @click="shows = false">取 消</el-button>
                    <el-button type="primary" @click="oks">确 定</el-button>
                </el-dialog>
                <!-- 批量删除 -->
                <el-dialog title="批量删除" v-model="centerDialogVisiblet" width="30%" center>
                    <div class="dialog-message">确认删除这批数据吗?</div>
                    <span slot="footer" class="dialog-footer">
                        <div></div>
                        <div>
                            <el-button @click="centerDialogVisiblet = false">取 消</el-button>
                            <el-button type="primary" @click="deleteid_t">确 定</el-button>
                        </div>
                    </span>
                </el-dialog>
            </el-card>

        </div>
        <!-- 第二块 -->
        <div v-show="activeStatud" class="edit-container">
            <el-card class="edit-card">
                <div class="edit-title">{{ addText }}</div>
                <div class="divider"></div>
                <div class="form-container">
                    <el-form ref="ruleFormRef" class="edit-form" :model="ruleForm" status-icon :rules="rules"
                        label-position="left" label-width="auto" >
                        <el-form-item label="分类名称" prop="name" class="form-item">
                            <el-input v-model.trim="ruleForm.name" placeholder="请输入" class="input-full-width" />
                        </el-form-item>
                    </el-form>
                    <div class="dialog-footer">
                        <el-button type="primary" @click="submitForm(ruleFormRef)">确认</el-button>
                        <el-button @click="closes(ruleFormRef)">取消</el-button>
                    </div>
                </div>
            </el-card>
        </div>
    </div>
</template>

<script setup>
// 保持原有script部分不变
import { ref, reactive } from 'vue';
import { group_list, group_add, group_del } from '../../../api/group/index'
import { ElMessage, ElCard } from 'element-plus';
const time = ref('')
// 创建数据变量
const activeList = ref([]);
const activeStatu = ref(true)
const activeStatud = ref(false)
const names = ref('导出');
import { inject } from 'vue'
const testFn = inject('testFn')
testFn()
const testName = inject('testName')
const dialogTableVisible = ref(false);
const statused = ref('1');
// 表格页码数
const inputed = ref('');
const inputeds = ref('');
const pageSize = ref(5);
const currentPage = ref(1);
const copyList = ref([]);
const files = ref(false);
const originalName = ref(''); // 存储编辑时的原始名称
// 请求接口并开局渲染
let tokens = JSON.parse(localStorage.getItem('tokens'));
console.log(tokens);
// 请求数据渲染
render();
function render() {
    group_list({
        token: tokens.token,
        uid: tokens.userinfo.id
    }, {
        userid: tokens.userinfo.id
    }).then((res) => {
        console.log(res);
        activeList.value = res.data;
        copyList.value = res.data;
    });
}
// 点击新增
const addText = ref("")
function add() {
    activeStatu.value = false
    addText.value = '添加'
    activeStatud.value = true
    dialogTableVisible.value = true;
    statused.value = '1';
    disableds.value = true;
    (ruleForm.name = ''), (ruleForm.start_time = ''), (ruleForm.end_time = ''), (ruleForm.details = ''), (ruleForm.img = ''), (ruleForm.synopsis = '');

}
// 表单对象
const ruleForm = reactive({
    name: '',
    start_time: '',
    end_time: '',
    details: '',
    img: '',
    synopsis: '',
});
// 查重机制
// 验证名称唯一性
const validateNameUnique = (rule, value, callback) => {
    if (!value) {
        callback();
        return;
    }

    // 如果是编辑状态且名称未改变，直接通过验证
    if (statused.value === '2' && value === originalName.value) {
        callback();
        return;
    }

    // 检查名称是否已存在
    const isExist = activeList.value.some(item =>
        item.title === value &&
        (statused.value === '1' || item.id !== ids.value)
    );

    if (isExist) {
        callback(new Error('分类名称已存在'));
    } else {
        callback();
    }
};
const ruleFormRef = ref('');
const rules = reactive({
    name: [
        {
            required: true,
            message: '请输入分类名称',
            trigger: 'blur',
        },
        {
            validator: validateNameUnique,
            trigger: 'blur'
        }
    ],
    start_time: [
        {
            required: true,
            message: '请选择开始时间',
            trigger: 'blur',
        },
    ],
    end_time: [
        {
            required: true,
            message: '请输入结束时间',
            trigger: 'blur',
        }, { validator: validateEmailDomain, trigger: 'blur' }
    ],
    details: [
        {
            required: true,
            message: '请输入活动详情',
            trigger: 'blur',
        },
    ],
    img: [
        {
            required: true,
            message: '请上传图片',
            trigger: 'change',
        },
    ],
    synopsis: [
        {
            required: true,
            trigger: 'blur',
            validator: (rule, value, callback) => {
                if (!value) {
                    callback(new Error('请输入活动简介'));
                } else if (value.length > 19) {
                    callback(new Error('仅最多输入20个字'));
                } else {
                    callback();
                }
            },
        },
    ],
});

// 结束时间不能大于开始时间
function validateEmailDomain(rule, value, callback) {
    if (value === '') {
        callback(new Error('结束时间不能为空'));
    } else if (value < ruleForm.start_time) {
        // 假设我们只允许 @example.com 的邮箱  
        callback(new Error('结束时间不能小于开始时间'));
    } else {
        callback();
    }
}
// 点击新增或编辑
const submitForm = (formEl) => {
    if (!formEl) return;
    formEl.validate((valid) => {
        if (valid) {
            // 如果是编辑且名称未改变，直接提交
            if (statused.value === '2' && ruleForm.name === originalName.value) {
                submitData();
                return;
            }

            // 检查名称是否重复
            const isExist = activeList.value.some(item =>
                item.title === ruleForm.name &&
                (statused.value === '1' || item.id !== ids.value)
            );

            if (isExist) {
                ElMessage({
                    message: '分类名称已存在',
                    type: 'warning',
                });
                return;
            }

            submitData();
        }
    });
};

// 提取提交数据的公共逻辑
function submitData() {
    if (statused.value == '1') {
        group_add(
            { token: tokens.token, uid: tokens.userinfo.id },
            { userid: tokens.userinfo.id, title: ruleForm.name, sort: 0 }
        ).then((res) => {
            if (res.code == '1') {
                ElMessage.success('新增成功');
                setTimeout(() => {
                    activeStatud.value = false;
                    activeStatu.value = true;
                }, 1200);
                render();
            }
        });
    } else if (statused.value == '2') {
        group_add(
            { token: tokens.token, uid: tokens.userinfo.id },
            { userid: tokens.userinfo.id, id: ids.value, title: ruleForm.name, sort: 0 }
        ).then((res) => {
            if (res.code == '1') {
                ElMessage.success('编辑成功');
                setTimeout(() => {
                    activeStatud.value = false;
                    activeStatu.value = true;
                }, 1200);
                render();
            } else {
                ElMessage.warning('编辑失败，请重试');
            }
        });
    }
}
// 编辑使用的id
const ids = ref('');
const disableds = ref(true);
// 关闭新增
const closes = (formEl) => {
    activeStatu.value = true;
    activeStatud.value = false;
    formEl.resetFields();
    formEl.clearValidate();
    dialogTableVisible.value = false;
    files.value = false;
    ruleForm.name = '';
    originalName.value = ''; // 清空原始名称
};
// 点击编辑
function edit(item) {
    addText.value = '编辑';
    ids.value = item.id;
    activeStatud.value = true;
    activeStatu.value = false;
    ruleForm.name = item.title;
    originalName.value = item.title; // 保存原始名称
    disableds.value = false;
    statused.value = '2';
}
// 点击上传出现弹窗
function deletes(item) {
    console.log(item);
    centerDialogVisible.value = true;
    deleteids.value = item.id;
}
const deleteids = ref('');
const centerDialogVisible = ref(false);
// 确认删除
function deleteid() {
    group_del(
        {
            token: tokens.token,
            uid: tokens.userinfo.id,
        },
        {
            userid: tokens.userinfo.id,
            ids: deleteids.value,
        }
    ).then((res) => {
        if (res.code == '1') {
            centerDialogVisible.value = false;
            ElMessage({
                message: '删除成功',
                type: 'success',
            });
            render();
        }
    });
}
// 分类名称搜索
function filters() {
    currentPage.value = 1
    console.log(inputed.value);
    let a = [];
    activeList.value = copyList.value.filter(function (item) {
        // 判断是否满足搜索条件
        if (String(item.title).indexOf(String(inputed.value)) > -1) {
            return a;
        }
    });
    currentPage.value = 1

}
// 分类日期搜索
const data_filters = () => {
    let end_time
    let start_time
    let ars = []
    if (time.value) {
        end_time = Date.parse(new Date(time.value[0]))
        start_time = Date.parse(new Date(time.value[1]))
    }
    activeList.value = copyList.value.filter((item) => {
        if (item.title ?
            item.title.indexOf(inputed.value) > -1 &&
            (time.value ?
                Date.parse(new Date(`${item.createtime}`)) > end_time &&
                Date.parse(new Date(` ${item.createtime}`)) < start_time : true
            ) : true
        ) {
            return item
        }
        ars.push(item)
        // console.log(item);
    });
}
const shows = ref(false);
// 删除批量
// 全选单选
const SelectArr = ref([])
const All_Delete = ref([])
const handleSelectionChange = (val) => {
    All_Delete.value = []
    SelectArr.value = val
    SelectArr.value.forEach(item => {
        console.log(item);
        All_Delete.value.push(item.id)
    })
    console.log(All_Delete.value);
}
// 批量删除
// 批量删除
const centerDialogVisiblet = ref(false)
const st = ref([])
function deleList() {
    st.value = []
    console.log(All_Delete.value);
    st.value.push(All_Delete.value)
    if (All_Delete.value == '') {
        ElMessage({
            message: '请勾选要删除的娱乐分类',
            type: 'warning',
        })
    } else {
        centerDialogVisiblet.value = true
    }
}
// 确认批量删除
const deleteid_t = () => {
    group_del({
        token: tokens.token,
        uid: tokens.userinfo.id
    }, {
        userid: tokens.userinfo.id,
        ids: st.value.join(','),

    }).then(res => {
        console.log(res, '删除成功或失败回调');
        centerDialogVisiblet.value = false;
        render();
        ElMessage({
            message: '删除成功',
            type: 'success',
        })
    })
}
</script>

<style>
/* 原有的样式 */
.text {
    font-size: 14px;
}

.item {
    margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
    display: table;
    content: '';
}

.clearfix:after {
    clear: both;
}

.box-card {
    display: flex;
    height: 300px;
    width: 90%;
}

.handle {
    display: flex;
    align-items: center;
    justify-content: center;
}

.paging {
    display: flex;
    justify-content: center;
    margin-top: 10px;
    height: 70px;
}

.flex {
    display: flex;
    align-items: center;
    padding-bottom: 10px;
}

.flexBox {
    display: flex;
    width: 100%;
    align-items: center;
}

.el-date-range-picker__content {
    box-sizing: border-box;
    float: left;
    margin: 0;
    padding: 16px;
    width: 38%;
}

/* 新增的样式，从内联样式迁移过来 */
.card-padding {
    padding: 10px;
}

.category-title {
    width: 220px;
}

.search-input {
    width: 220px;
}

.date-picker-container {
    margin-left: 20px;
}

.date-picker {
    width: 220px;
}

.button-group {
    display: flex;
}

.data-table {
    margin-top: 10px;
    width: 100%;
}

.edit-btn {
    color: rgba(64, 158, 255, 1);
    cursor: pointer;
}

.delete-btn {
    color: red;
    cursor: pointer;
}

.button-spacing {
    width: 10px;
}

.dialog-message {
    font-size: 16px;
    padding-bottom: 20px;
}

.dialog-buttons {
    display: flex;
    justify-content: end;
}

.edit-container {
    padding: 10px;
}

.edit-card {
    width: 96%;
    margin-left: 2%;
    margin-top: 1%;
    position: relative;
    height: 80vh;
}

.edit-title {
    padding: 10px;
}

.divider {
    width: 100%;
    height: 1px;
    background-color: rgba(195, 195, 195, 1);
}

.form-container {
    margin-top: 50px;
    margin-left: 100px;
}

.edit-form {
    width: 40%;
}

.form-item {
    width: 100%;
}

.input-full-width {
    width: 100%;
}

.dialog-footer {
    position: absolute;
    bottom: 20px;
    right: 40px;
}
</style>